<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>






<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="iOS,安全攻防," />





  <link rel="alternate" href="/atom.xml" title="Bingo's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1" />






<meta name="description" content="前言终于开始做攻防相关的操作了，我会一边攻一边防，这篇文章先介绍一个简单的代码混淆的防备操作。文章会从为何要加密、加密市场市场现状、加密思路、方法、工具、操作等方面进行阐述，也作为我个人的记录以便日后的回顾。">
<meta name="keywords" content="iOS,安全攻防">
<meta property="og:type" content="article">
<meta property="og:title" content="Objective-C 代码混淆">
<meta property="og:url" content="https://bingozb.github.io/17.html">
<meta property="og:site_name" content="Bingo's Blog">
<meta property="og:description" content="前言终于开始做攻防相关的操作了，我会一边攻一边防，这篇文章先介绍一个简单的代码混淆的防备操作。文章会从为何要加密、加密市场市场现状、加密思路、方法、工具、操作等方面进行阐述，也作为我个人的记录以便日后的回顾。">
<meta property="og:image" content="https://bingozb.github.io/images/blog/17/confuse.png">
<meta property="og:image" content="https://bingozb.github.io/images/blog/17/obscure.png">
<meta property="og:image" content="https://bingozb.github.io/images/blog/17/codeObscure.png">
<meta property="og:updated_time" content="2017-09-22T17:30:21.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Objective-C 代码混淆">
<meta name="twitter:description" content="前言终于开始做攻防相关的操作了，我会一边攻一边防，这篇文章先介绍一个简单的代码混淆的防备操作。文章会从为何要加密、加密市场市场现状、加密思路、方法、工具、操作等方面进行阐述，也作为我个人的记录以便日后的回顾。">
<meta name="twitter:image" content="https://bingozb.github.io/images/blog/17/confuse.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: 'JE30EVH7NI',
      apiKey: '862bb3deb9a3166ed99de0be6527f59c',
      indexName: 'blog',
      hits: {"per_page":10},
      labels: {"input_placeholder":"输入关键词进行搜索","hits_empty":"找不到关于「 ${query} 」的文章","hits_stats":"共找到 ${hits} 篇文章，花了 ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://bingozb.github.io/17.html"/>





  <title>Objective-C 代码混淆 | Bingo's Blog</title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?c8a59b9753bce3ec58f81c89e2acce96";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Bingo's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Stay Hungry, Stay Foolish.</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocapitalize="off" autocomplete="off" autocorrect="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://bingozb.github.io/17.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Bingo">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Bingo's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Objective-C 代码混淆
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-02-19T02:21:41+08:00">
                2017-02-19
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/解决方案/" itemprop="url" rel="index">
                    <span itemprop="name">解决方案</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-comment-o"></i>
              </span>
              
                <a href="/17.html#SOHUCS" itemprop="discussionUrl">
                  <span id="changyan_count_unit" class="post-comments-count hc-comment-count" data-xid="17.html" itemprop="commentsCount"></span>
                </a>
              
            
          

          
          
             <span id="/17.html" class="leancloud_visitors" data-flag-title="Objective-C 代码混淆">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数 </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>终于开始做攻防相关的操作了，我会一边攻一边防，这篇文章先介绍一个简单的代码混淆的防备操作。文章会从为何要加密、加密市场市场现状、加密思路、方法、工具、操作等方面进行阐述，也作为我个人的记录以便日后的回顾。</p>
<a id="more"></a>
<h2 id="为什么要做混淆加密"><a href="#为什么要做混淆加密" class="headerlink" title="为什么要做混淆加密"></a>为什么要做混淆加密</h2><p>先说安卓，是一定要做混淆加密的。因为 apk 非常容易反编译，比如用 smail2java，apk 文件反编译过后都会变成 smail 文件，通过这个工具能看到里面的 Java 代码，请注意，看到的是源码！没有混淆的代码一旦经过反编译全部完完全全的展现给别人，知识产权一点保障也没有。如果写了什么敏感信息，也就全部暴露了。而加固后，比如用360加固保后，反编译出来基本什么也看不到了。</p>
<p>再说 iOS，使用 classdump 对原程序进行 dump，可以 dump 出所有源程序的函数所有信息，包括源程序所有函数类型，变量全部泄露。又比如用 IDA 或者 Hopper Disassembler， 虽然不能像安卓一样反编译出源代码，但还是可以看到汇编或者汇编与 OC 运行时的结合体，还是可以比较容易看出方法的具体实现，让攻击者，也就是黑客们了解了程序结构方便逆向，所以也需要做混淆加密。</p>
<h2 id="加密市场"><a href="#加密市场" class="headerlink" title="加密市场"></a>加密市场</h2><p>国内市场上的现状是安卓的加固烂大街，并且免费，比如360加固保。对于安卓来说，自己写混淆加密意义不大，当然基于了解与学习的角度出发，Get 一项新技能完全没毛病。</p>
<p>而 iOS 市场上很少有人做混淆，因为不能像安卓基于平台化的提交应用包，只能使用第三方提供的集成了加密插件的 Xcode，代替官方原版 Xcode 来打包。国内首家做 iOS 加密的爱加密，据我的深度了解购买授权需要八万块，这可是一笔很大的成本。对于安全级别本身就比较高的苹果应用来说，其实不需要再做太多太多的安全防范操作了。自己学会较简单的混淆加密原理与操作，就可以省下一笔钱了。接下来就只说 iOS 的混淆加密。</p>
<h2 id="iOS-混淆加密"><a href="#iOS-混淆加密" class="headerlink" title="iOS 混淆加密"></a>iOS 混淆加密</h2><h3 id="混淆思路"><a href="#混淆思路" class="headerlink" title="混淆思路"></a>混淆思路</h3><ul>
<li>花代码花指令</li>
<li>易读字符替换</li>
</ul>
<p>花代码花指令即随意往程序中加入迷惑人的代码指令，但是个人觉得这个方法还是不太好，如果开发阶段加入迷惑人的代码，容易连开发者自己都被迷惑；如果上架前加入迷惑人的代码，以后的版本迭代也会比较恶心，所以个人不推荐用这个方法。</p>
<p>易读字符替换是防止 class-dump 出可读信息的非常有效的办法，例如将方法名混淆。</p>
<h3 id="混淆的时机"><a href="#混淆的时机" class="headerlink" title="混淆的时机"></a>混淆的时机</h3><ul>
<li>开发时一直保留清晰可读的程序代码，方便自己。</li>
<li>发布时编译出来的二进制包含乱七八糟的混淆后的程序代码，恶心他人。</li>
</ul>
<p>因此，我们可以在 <strong>Build Phrase</strong> 中设定在编译之前进行方法名的字符串替换。</p>
<h3 id="混淆的方法"><a href="#混淆的方法" class="headerlink" title="混淆的方法"></a>混淆的方法</h3><p>方法名混淆其实就是字符串替换，利用 #define 的方法来完成，可以把混淆结果合并在一个 .h 中，在工程 Prefix.pch 的最前面 #import 这个 .h。不导入也可以编译、导入则实现混淆。</p>
<p>单段的 selector，如 func: ，可以通过 #define func 来实现字符串替换。<br>多段的 selector，如 a:b:c: ，可以通过分别 #define a 、b、c 来实现字符串替换。</p>
<h3 id="混淆工具"><a href="#混淆工具" class="headerlink" title="混淆工具"></a>混淆工具</h3><p>写一个的混淆脚本，主要思路是把敏感方法名集中写在一个名叫 func.list 的文件中，逐一 #define 成随机字符，追加写入 .h。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div></pre></td><td class="code"><pre><div class="line"><span class="meta">#!/usr/bin/env bash</span></div><div class="line"></div><div class="line">TABLENAME=symbols</div><div class="line">SYMBOL_DB_FILE=<span class="string">"symbols"</span></div><div class="line">STRING_SYMBOL_FILE=<span class="string">"func.list"</span></div><div class="line">HEAD_FILE=<span class="string">"<span class="variable">$PROJECT_DIR</span>/<span class="variable">$PROJECT_NAME</span>/Classes/Other/DKCodeObscure.h"</span></div><div class="line"><span class="built_in">export</span> LC_CTYPE=C</div><div class="line"></div><div class="line"><span class="comment">#维护数据库方便日后作排重</span></div><div class="line"><span class="function"><span class="title">createTable</span></span>()</div><div class="line">&#123;</div><div class="line">    <span class="built_in">echo</span> <span class="string">"create table <span class="variable">$TABLENAME</span>(src text, des text);"</span> | sqlite3 <span class="variable">$SYMBOL_DB_FILE</span></div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="title">insertValue</span></span>()</div><div class="line">&#123;</div><div class="line">    <span class="built_in">echo</span> <span class="string">"insert into <span class="variable">$TABLENAME</span> values('<span class="variable">$1</span>' ,'<span class="variable">$2</span>');"</span> | sqlite3 <span class="variable">$SYMBOL_DB_FILE</span></div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="title">query</span></span>()</div><div class="line">&#123;</div><div class="line">    <span class="built_in">echo</span> <span class="string">"select * from <span class="variable">$TABLENAME</span> where src='<span class="variable">$1</span>';"</span> | sqlite3 <span class="variable">$SYMBOL_DB_FILE</span></div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="title">ramdomString</span></span>()</div><div class="line">&#123;</div><div class="line">    openssl rand -base64 64 | tr -cd <span class="string">'a-zA-Z'</span> |head -c 16</div><div class="line">&#125;</div><div class="line"></div><div class="line">rm <span class="_">-f</span> <span class="variable">$SYMBOL_DB_FILE</span></div><div class="line">rm <span class="_">-f</span> <span class="variable">$HEAD_FILE</span></div><div class="line">createTable</div><div class="line"></div><div class="line">touch <span class="variable">$HEAD_FILE</span></div><div class="line"><span class="built_in">echo</span> <span class="string">'#ifndef Demo_codeObfuscation_h</span></div><div class="line">#define Demo_codeObfuscation_h' &gt;&gt; <span class="variable">$HEAD_FILE</span></div><div class="line"><span class="built_in">echo</span> <span class="string">"//confuse string at `date`"</span> &gt;&gt; <span class="variable">$HEAD_FILE</span></div><div class="line">cat <span class="string">"<span class="variable">$STRING_SYMBOL_FILE</span>"</span> | <span class="keyword">while</span> <span class="built_in">read</span> -ra line; <span class="keyword">do</span></div><div class="line">    <span class="keyword">if</span> [[ ! -z <span class="string">"<span class="variable">$line</span>"</span> ]]; <span class="keyword">then</span></div><div class="line">        ramdom=`ramdomString`</div><div class="line">        <span class="built_in">echo</span> <span class="variable">$line</span> <span class="variable">$ramdom</span></div><div class="line">        insertValue <span class="variable">$line</span> <span class="variable">$ramdom</span></div><div class="line">        <span class="built_in">echo</span> <span class="string">"#define <span class="variable">$line</span> <span class="variable">$ramdom</span>"</span> &gt;&gt; <span class="variable">$HEAD_FILE</span></div><div class="line">    <span class="keyword">fi</span></div><div class="line"><span class="keyword">done</span></div><div class="line"><span class="built_in">echo</span> <span class="string">"#endif"</span> &gt;&gt; <span class="variable">$HEAD_FILE</span></div><div class="line"></div><div class="line">sqlite3 <span class="variable">$SYMBOL_DB_FILE</span> .dump</div></pre></td></tr></table></figure>
<h3 id="操作步骤"><a href="#操作步骤" class="headerlink" title="操作步骤"></a>操作步骤</h3><ol>
<li><p>将混淆脚本 confuse.sh 放到工程目录下</p>
 <figure class="highlight livescript"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">mv confuse.sh <span class="keyword">to</span><span class="regexp">/project/path/</span></div></pre></td></tr></table></figure>
</li>
<li><p>创建混淆头文件 DKCodeObscure.h</p>
<p> 可以直接在 xcode 中新建一个 Header 文件，根据项目架构分层找一个适当的位置放，我把它放在了 <code>/Classes/Other/</code>下，要与 confuse.sh 里的 HEAD_FILE 保持一致。</p>
 <figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">HEAD_FILE=<span class="string">"<span class="variable">$PROJECT_DIR</span>/<span class="variable">$PROJECT_NAME</span>/Classes/Other/DKCodeObscure.h"</span></div></pre></td></tr></table></figure>
</li>
<li><p>修改 pch，添加混淆头文件</p>
 <figure class="highlight cpp"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="meta">#<span class="meta-keyword">ifdef</span> __OBJC__</span></div><div class="line">   <span class="meta">#import <span class="meta-string">"DKCodeObscure.h"</span></span></div><div class="line"><span class="meta">#<span class="meta-keyword">endif</span></span></div></pre></td></tr></table></figure>
</li>
<li><p>配置 Build Phase，添加执行脚本操作</p>
<p> 新建一个 Run Script，输入<code>$PROJECT_DIR/confuse.sh</code></p>
<p> <img src="images/blog/17/confuse.png" alt="confuse.png"></p>
</li>
<li><p>创建函数名列表 func.list，根据规则写入待混淆的方法名</p>
<p> 例如:</p>
 <figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/** 获取立即支付前的准备数据 */</span></div><div class="line">+ (<span class="keyword">void</span>)fetchPreDataWithProductId:(<span class="built_in">NSString</span> *)productId quantity:(<span class="built_in">NSInteger</span>)quantity callback:(<span class="keyword">void</span>(^)(DKPayPreData *preData, <span class="built_in">NSError</span> *error))callback;</div></pre></td></tr></table></figure>
<p> 可写成：</p>
 <figure class="highlight ebnf"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="attribute">fetchPreDataWithProductId</span></div><div class="line">quantity</div><div class="line">callback</div></pre></td></tr></table></figure>
<p> 一般情况下，需要混淆加密的方法应该只是一些比较敏感的，比如与支付相关的 API Service 等。当然，如果需要写入混淆的方法名太多了，一个一个写也是很麻烦，后面我会写一个根据规则自动生成所有方法名列表的脚本。</p>
</li>
<li><p>将 func.list 文件放置于与 confuse.sh 脚本同级</p>
<figure class="highlight applescript"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">mv func.<span class="built_in">list</span> <span class="keyword">to</span>/project/path/</div></pre></td></tr></table></figure>
</li>
<li><p>编译查看结果</p>
<p> 直接 build，混淆脚本会在编译前运行，进行字符随机替换，并且每次 build 的随机字符不同，如图：</p>
<p> <img src="images/blog/17/obscure.png" alt="obscure.png"></p>
<p> 同时也会将混淆记录写在 DKCodeObscure.h 中</p>
<p> <img src="images/blog/17/codeObscure.png" alt="DKCodeObscure.h"></p>
</li>
</ol>
<h3 id="补充"><a href="#补充" class="headerlink" title="补充"></a>补充</h3><p>如果 Build 的时候报了如下一个错误：</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">Shell Script Invocation Error</div><div class="line"></div><div class="line"><span class="regexp">/Users/</span>bingo<span class="regexp">/Library/</span>Developer<span class="regexp">/Xcode/</span>DerivedData<span class="regexp">/SF-cprhxwzvzucuawewgvpjhoffdayp/</span>Build<span class="regexp">/Intermediates/</span>SF.build<span class="regexp">/Debug-iphoneos/</span>SF.build/Script-D71BDF821E5C99F4003BF126.<span class="string">sh:</span> </div><div class="line">line <span class="number">2</span>: <span class="regexp">/Users/</span>bingo<span class="regexp">/Desktop/</span>iOS/<span class="string">iOS:</span> No such file or directory</div></pre></td></tr></table></figure>
<p>这是路径有问题，比如包含空格，我的 PROJECT_DIR 是 <code>/Users/bingo/Desktop/iOS/iOS\ Project/SF</code>，“iOS Project” 中间有空格，但是 Script 不会自动转义，所以要保证路径不能有空格，例如我改成了 “iOS_Project”。（中文路径还没测试，有可能没问题，但我的看法作为一个有逼格的 developer，用中文你还是别 do 了吧。）</p>
<h2 id="后话"><a href="#后话" class="headerlink" title="后话"></a>后话</h2><p>至此，一个 iOS 方法名混淆加密就完成了，但还是很简单的，后面会再一步步优化，现在的 ramdomString() 方法每次都是生成随机字符，后面可能会考虑改成 md5 加密，还有写个脚本一键生成 func.list，还考虑将创建文件等操作也改成用脚本来生成等等。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        
  <ul class="post-copyright">
    <li class="post-copyright-author">
      <strong>本文作者：</strong>
      Bingo
    </li>
    <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://bingozb.github.io/17.html" title="Objective-C 代码混淆">https://bingozb.github.io/17.html</a>
    </li>
    <li class="post-copyright-license">
      <strong>版权声明： </strong>
      本博客所有文章除特别声明外，均采用 MIT 许可协议。转载请注明出处！
    </li>
  </ul>


      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/iOS/" rel="tag"># iOS</a>
          
            <a href="/tags/安全攻防/" rel="tag"># 安全攻防</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/18.html" rel="next" title="iOS10.2 非完美越狱">
                <i class="fa fa-chevron-left"></i> iOS10.2 非完美越狱
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/16.html" rel="prev" title="移动端规划大纲">
                移动端规划大纲 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="SOHUCS"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.jpg"
               alt="Bingo" />
          <p class="site-author-name" itemprop="name">Bingo</p>
           
              <p class="site-description motion-element" itemprop="description">He who hesitates is lost.</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">55</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">4</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">22</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/bingozb" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://coding.net/u/bingozb" target="_blank" title="Coding">
                  
                    <i class="fa fa-fw fa-git"></i>
                  
                  Coding
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/bingo_v587" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.facebook.com/profile.php?id=100013406670597" target="_blank" title="Facebook">
                  
                    <i class="fa fa-fw fa-facebook"></i>
                  
                  Facebook
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#为什么要做混淆加密"><span class="nav-number">2.</span> <span class="nav-text">为什么要做混淆加密</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#加密市场"><span class="nav-number">3.</span> <span class="nav-text">加密市场</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#iOS-混淆加密"><span class="nav-number">4.</span> <span class="nav-text">iOS 混淆加密</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#混淆思路"><span class="nav-number">4.1.</span> <span class="nav-text">混淆思路</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#混淆的时机"><span class="nav-number">4.2.</span> <span class="nav-text">混淆的时机</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#混淆的方法"><span class="nav-number">4.3.</span> <span class="nav-text">混淆的方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#混淆工具"><span class="nav-number">4.4.</span> <span class="nav-text">混淆工具</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#操作步骤"><span class="nav-number">4.5.</span> <span class="nav-text">操作步骤</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#补充"><span class="nav-number">4.6.</span> <span class="nav-text">补充</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#后话"><span class="nav-number">5.</span> <span class="nav-text">后话</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  Copyright © 
  <span itemprop="copyrightYear">2017
  </span>
  <span class="author" itemprop="copyrightHolder">Bingo
  </span>
  All rights reserved.
</div>
        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script>



  


  




	





  





  





  




  
    <script type="text/javascript">
    (function(){
      var appid = 'cytcdzpa3';
      var conf = 'c0c6117021d1cea9f11629100efd8446';
      var width = window.innerWidth || document.documentElement.clientWidth;
      if (width < 960) {
      window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){
        window.changyan.api.config({appid:appid,conf:conf})});
      }
    })();
    </script>
    <script type="text/javascript" src="https://assets.changyan.sohu.com/upload/plugins/plugins.count.js"></script>
  



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (search_path.endsWith("json")) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      $('#local-search-input').focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('-1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("A9MeTkIR49W9kOOSvkggsXge-gzGzoHsz", "HaIEOSDyxpcjwOjRjCYxiWjA");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

  

  

</body>
</html>
